package com.lanswon.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanswon.common.util.TreeNode;
import com.lanswon.dao.TypeManageMapper;
import com.lanswon.entity.TypeManage;

@Service
public class TypeManageService {

	@Autowired
	private TypeManageMapper typeManageMapper;
	
	
	/**
	 * 获取所有子父类型
	 * @return
	 */
	public List<TreeNode> getTypeManageTreeList() {
		List<TypeManage> tmList = typeManageMapper.selectTypeManageList();
		List<TreeNode> parentList = new ArrayList<>();
		List<TreeNode> childList = new ArrayList<>();
		for (TypeManage tm : tmList) {
			TreeNode tn = new TreeNode();
			tn.setId(String.valueOf(tm.getId()));
			tn.setName(tm.getName());
			tn.setParentId(String.valueOf(tm.getParentId()));
			if(tm.getParentId()==null) {
				parentList.add(tn);
			}else {                               
				childList.add(tn);
			}
		}
		for (TreeNode pNode : parentList) {
			List<TreeNode> childList2 = new ArrayList<>();
			for (TreeNode cNode : childList) {
				if(cNode.getParentId().equals(pNode.getId())) {
					childList2.add(cNode);
				}
			}
			pNode.setChildrenList(childList2);
		}
		return parentList; 
	}


	public List<TypeManage> getParentTypeList() {
		return typeManageMapper.selectParentTypeList();
	}


	public List<TypeManage> pageList(Map<String, Object> map) {
		return typeManageMapper.selectTypePageList(map);
	}


	public Integer pageListCount(Map<String, Object> map) {
		return typeManageMapper.selectTypePageListCount(map);
	}


	public TypeManage getTypeById(Long id) {
		return typeManageMapper.selectByPrimaryKey(id);
	}


	public void updateType(TypeManage tyManage) {
		tyManage.setUpdateTime(new Date());
		typeManageMapper.updateByPrimaryKeySelective(tyManage);
	}


	public void addType(TypeManage tyManage) {
		Date d = new Date();
		tyManage.setCreateTime(d);
		tyManage.setUpdateTime(d);
		typeManageMapper.insert(tyManage);
	}


	public TypeManage getTypeByName(String name) {
		return typeManageMapper.selectTypeByName(name);
	}


	public void typeDel(Long id) {
		typeManageMapper.deleteByPrimaryKey(id);
	}
	
}
